<template>
  <div class="station-selector">
    <div class="selector-content">
      <!-- 左侧：可选站点 -->
      <div class="available-stations">
        <h4>可选站点</h4>
        <el-input
          v-model="searchKeyword"
          placeholder="搜索站点"
          prefix-icon="el-icon-search"
          size="small"
          style="margin-bottom: 10px;">
        </el-input>
        <div class="stations-list">
          <div
            v-for="station in filteredAvailableStations"
            :key="station.id"
            class="station-item available"
            @click="addStation(station)">
            <i class="el-icon-plus"></i>
            <span>{{ station.stationName }}</span>
          </div>
        </div>
      </div>

      <!-- 右侧：已选站点（可排序） -->
      <div class="selected-stations">
        <h4>线路站点（拖拽排序）</h4>
        <div v-if="internalSelectedStations.length === 0" class="empty-hint">
          请从左侧选择站点
        </div>
        <draggable
          v-model="internalSelectedStations"
          class="stations-list"
          group="stations"
          @end="onDragEnd">
          <div
            v-for="(station, index) in internalSelectedStations"
            :key="station.stationId || station.id"
            class="station-item selected">
            <div class="station-info">
              <span class="station-order">{{ index + 1 }}</span>
              <span class="station-name">{{ getStationName(station) }}</span>
            </div>
            <div class="station-details">
              <el-input-number
                v-model="station.distanceFromStart"
                :min="0"
                :precision="2"
                size="mini"
                placeholder="距离(km)"
                style="width: 100px;">
              </el-input-number>
              <el-input-number
                v-model="station.estimatedArrivalTime"
                :min="0"
                size="mini"
                placeholder="时间(分)"
                style="width: 80px; margin-left: 5px;">
              </el-input-number>
              <el-button
                type="danger"
                size="mini"
                icon="el-icon-delete"
                @click="removeStation(index)"
                style="margin-left: 5px;">
              </el-button>
            </div>
          </div>
        </draggable>
      </div>
    </div>

    <!-- 操作按钮 -->
    <div class="dialog-footer">
      <el-button @click="handleCancel">取 消</el-button>
      <el-button type="primary" @click="handleConfirm">确 定</el-button>
    </div>
  </div>
</template>

<script>
import draggable from 'vuedraggable'

export default {
  name: 'StationSelector',
  components: {
    draggable
  },
  props: {
    stationsList: {
      type: Array,
      default: () => []
    },
    selectedStations: {
      type: Array,
      default: () => []
    }
  },
  data() {
    return {
      searchKeyword: '',
      internalSelectedStations: []
    }
  },
  computed: {
    // 过滤可选站点（排除已选择的）
    filteredAvailableStations() {
      const selectedIds = this.internalSelectedStations.map(s => s.stationId || s.id)
      return this.stationsList.filter(station => {
        const matchesSearch = !this.searchKeyword ||
          station.stationName.toLowerCase().includes(this.searchKeyword.toLowerCase())
        const notSelected = !selectedIds.includes(station.id)
        return matchesSearch && notSelected
      })
    }
  },
  watch: {
    selectedStations: {
      handler(newVal) {
        this.internalSelectedStations = JSON.parse(JSON.stringify(newVal))
      },
      immediate: true,
      deep: true
    }
  },
  methods: {
    // 添加站点到已选列表
    addStation(station) {
      console.log('添加站点:', station)
      this.internalSelectedStations.push({
        id: station.id,
        stationId: station.id,
        stationName: station.stationName,
        distanceFromStart: 0,
        estimatedArrivalTime: 0
      })
    },

    // 移除站点
    removeStation(index) {
      this.internalSelectedStations.splice(index, 1)
    },

    // 获取站点名称
    getStationName(station) {
      if (station.stationName) return station.stationName
      const foundStation = this.stationsList.find(s => s.id === (station.stationId || station.id))
      return foundStation ? foundStation.stationName : '未知站点'
    },

    // 拖拽结束事件
    onDragEnd() {
      // 拖拽结束后，站点顺序已经自动更新
    },

    // 确认选择
    handleConfirm() {
      this.$emit('confirm', this.internalSelectedStations)
    },

    // 取消选择
    handleCancel() {
      this.$emit('cancel')
    }
  }
}
</script>

<style scoped>
.station-selector {
  height: 500px;
  display: flex;
  flex-direction: column;
}

.selector-content {
  display: flex;
  flex: 1;
  gap: 20px;
}

.available-stations,
.selected-stations {
  flex: 1;
  border: 1px solid #dcdfe6;
  border-radius: 4px;
  padding: 15px;
}

.available-stations h4,
.selected-stations h4 {
  margin: 0 0 15px 0;
  color: #606266;
}

.stations-list {
  max-height: 350px;
  overflow-y: auto;
}

.station-item {
  padding: 8px 12px;
  margin-bottom: 8px;
  border-radius: 4px;
  cursor: pointer;
  transition: background-color 0.3s;
}

.station-item.available {
  background-color: #f5f7fa;
  border: 1px dashed #c0c4cc;
}

.station-item.available:hover {
  background-color: #ecf5ff;
  border-color: #409eff;
  color: #409eff;
}

.station-item.selected {
  background-color: #fff;
  border: 1px solid #e4e7ed;
  cursor: move;
}

.station-item.selected:hover {
  background-color: #f5f7fa;
}

.station-info {
  display: flex;
  align-items: center;
  margin-bottom: 8px;
}

.station-order {
  display: inline-block;
  width: 20px;
  height: 20px;
  background-color: #409eff;
  color: white;
  border-radius: 50%;
  text-align: center;
  line-height: 20px;
  font-size: 12px;
  margin-right: 8px;
}

.station-name {
  font-weight: 500;
  color: #303133;
}

.station-details {
  display: flex;
  align-items: center;
  gap: 5px;
}

.empty-hint {
  text-align: center;
  color: #909399;
  padding: 50px 0;
}

.dialog-footer {
  padding-top: 15px;
  text-align: right;
  border-top: 1px solid #e4e7ed;
  margin-top: 15px;
}
</style>